import win32con as w32
import ctypes as ct
from PyQt4.QtGui import QMessageBox
import sys
import logging

import config

user32 = ct.windll.user32
logger = logging.getLogger(__name__)

try:
	from osdep.win import sendpaste
except ImportError:
	sendpaste = None
	logger.warn("Could not load sendpaste c module")

class PlatformSpecificCode:
	_MESSAGE_ID = 1

	_MODIFIER_TRANSFORMER = {config.MOD_ALT: w32.MOD_ALT, config.MOD_SHIFT: w32.MOD_SHIFT,
							 config.MOD_CONTROL: w32.MOD_CONTROL, config.MOD_WIN: w32.MOD_WIN }

	def __init__(self, *args, **kwargs):
		if sendpaste:
			# if modifier is ctrl we use simple version, otherwise complex one
			if config.hotkey[0] == (config.MOD_CONTROL,):
				paste_function = sendpaste.send_paste_simple
				logger.info("Use simple sendpaste")
			else:
				paste_function = sendpaste.send_paste
				logger.info("Use complex sendpaste")
		else:
			paste_function = lambda: None	# do nothing
		self._paste_text = paste_function
		super().__init__(*args, **kwargs)

	def register_hotkey(self):
		hwnd = int(self.winId())
		modifiers, key = self._get_hotkey()
		if key.islower():
			key = key.upper()
			logger.warn("hotkey character should be uppercase")
		key = ord(key)
		if not user32.RegisterHotKey(hwnd, self._MESSAGE_ID, modifiers, key):
			QMessageBox.critical(None, "Error", "Could not register hotkey")
			sys.exit(1)

	def _get_hotkey(self):
		modifiers, key = config.hotkey
		combined_mod = 0
		for m in modifiers:
			try:
				combined_mod |= self._MODIFIER_TRANSFORMER[m]
			except KeyError:
				logger.warn("Invalid modifier for windows - ignored.")
		if combined_mod == 0:
			logger.warn("No shortcut modifier or only invalid ones specified. Use ctrl as default.")
			return w32.MOD_CONTROL, key
		return combined_mod, key

	def unregister_hotkey(self):
		hwnd = int(self.winId())
		user32.UnregisterHotKey(hwnd, self._MESSAGE_ID)

	def winEvent(self, msg):
		if msg.message == w32.WM_HOTKEY:
			self.next_token()
			return True, id(msg)
		return False, id(msg)

	def set_taskbar_text(self, text):
		hwnd = int(self.winId())
		user32.SetWindowTextW(hwnd, text)
